

import soapp
import Eelay
import AsyncDisplayKit

public class SharePanel:JoView{
    
    var from:MoShare? = nil{
        didSet{
            if let f = from{
                content.row1 = f._plats.mutable_array
                content.row2 = f._actions.mutable_array
            }
        }
    }
    enum Result {
        case canle
        case success
        case unkown
    }
    
    typealias CallBack = (Result)->Void
    static var panels = [SharePanel]()
    static func remove(panel:SharePanel){
        var i:Int? = nil
        var n = 0
        for p in panels {
            if panel === p{
                i = n
            }
            n = n + 1
        }
        if let index = i{
            panels.remove(at: index)
        }
    }
    
    var cons:[NSLayoutConstraint] = []
    open var back:UIView?{
        get{
            if let bk = self.backView{
                return bk
            }
            return UIWindow.topWindow
//            var back:UIView? = UIApplication.shared.keyWindow
//            if back == nil{
//                back = UIApplication.shared.keyWindow?.rootViewController?.view
//            }
//            return back
         }
    }
     
    weak var backView:UIView? = nil
    var touchBk = UIView()
    var contentView = UIView()
    public func show() {
        if let bk = back{
           cons = bk.setEeLays(lays: [
                [self,[ee.T.L.B.R]]
            ]).1
        }
        touchBk.backgroundColor = .color(light: "#55555555", dark: "#11111122")
        bottomC.constant = 280
        contentView.setNeedsLayout()
        contentView.layoutIfNeeded()
        setNeedsLayout()
        layoutIfNeeded()

        touchBk.alpha = 0;
        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationDuration(0.25)
        UIView.setAnimationCurve(UIView.AnimationCurve.init(rawValue: 7) ?? .easeIn)
        bottomC.constant = 0
        touchBk.alpha = 1
        contentView.setNeedsLayout()
        contentView.layoutIfNeeded()
        setNeedsLayout()
        layoutIfNeeded()
        UIView.commitAnimations()
    }
    
    var info:NSMutableDictionary? = nil
    func share(_ info:NSMutableDictionary) {
        self.info = info
        show()
    }
    
    public func hide() {
        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationDuration(0.25)
        UIView.setAnimationCurve(UIView.AnimationCurve.init(rawValue: 7) ?? .easeIn)
        bottomC.constant = 280
        touchBk.alpha = 0
        contentView.setNeedsLayout()
        contentView.layoutIfNeeded()
        setNeedsLayout()
        layoutIfNeeded()
        UIView.commitAnimations()
        co_delay(delay: 0.25) {[weak self] in
            guard let ws = self else{return}
            self?.back?.removeConstraints(ws.cons)
            self?.removeFromSuperview()
            SharePanel.remove(panel: ws)
        }
    }
    
    
    
    public override func addLayoutRules() {
        SharePanel.panels.append(self)
        self.eelay = [
            [touchBk,[ee.T.L.B.R]]
        ]
        bridge.setContentConstrainToHighLever()
        contentView.eelay = [
            [bridge,[ee.T.L.R.safe],[ee.B.safe]]
        ]
        if let c = self.setEeLays(lays: [
            [contentView,[ee.L.R.B]]
        ]).1.last
        {
            bottomC = c
        }
        
        bridge.node = content
        content.confirmItem = {[weak self]
            item in
            self?.parserConfirm(item: item)
            self?.close()
        }
        touchBk.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(close)))
        contentView.backgroundColor = ._cellBackground
    
//        contentView.alpha = 0
//        co_delay(delay: 0.01) {[weak self] in
//            guard let ws = self else{return}
//            ws.bottomC.constant = -ws.contentView.frame.size.height
//            ws.contentView.alpha = 1
//            ws.contentView.setNeedsLayout()
//            ws.contentView.layoutIfNeeded()
//        }
    }
    
    func parserConfirm(item:NSMutableDictionary) {
        
        guard let from = self.from else {
            return
        }
        let ID = item[int:"id",-1]
        if from._clicked(item){
            if let plat = SharePlatform(rawValue: ID)
            {
                switch plat {
                case .copy_link:
                    MoToast.share.do(mode: .info("已经复制内容连接".loc))
                    UIPasteboard.general.string = from.shareInfo["link",""]
                default:
    //                break
                    plat.share(from: from)
                }
            }
        }
        
        
    }
    var bottomC = NSLayoutConstraint()
    
    @objc func close(){
        hide()
    }
    
    
    
    struct Setting {
        static var shareItems:[[String:Any]] = [
            ["title":"微信好友","icon":"mosdk-share-wx","id":SharePlatform.wx_friend.rawValue],
            ["title":"朋友圈","icon":"mosdk-share-pyq","id":SharePlatform.wx_pengyquan.rawValue],
//            ["title":"QQ","icon":"mosdk-share-qq","id":SharePlatform.wx_pengyquan.rawValue],
//            ["title":"微博","icon":"mosdk-share-wb","id":SharePlatform.wx_pengyquan.rawValue],

        ]
        static var actionItems:[[String:Any]] = [
            ["title":"分享链接","icon":"mosdk-pan-link","id":SharePlatform.copy_link.rawValue],
        ]
        
        static var colums = 4
        static var backgroundColor = UIColor._background
        static var foregroundColor = UIColor._foreground
        static var padding:UIEdgeInsets = [10,25,10,25]
        static var iconSize:CGSize = [44,76]
        static var iconSpace:CGFloat{
            get{
                return (Swidth - colums.cg_floatValue * iconSize.width - padding.left - padding.right)/(colums - 1).cg_floatValue
            }
        }
    }
    
    class Kit:JoCellNode{
        let iconN = ASImageNode()
        let nameN = ASTextNode2()
        override func specGetter() -> _Spec {
            return .stack(["v|7",&-.center], childs: [
                iconN["44",44],
                nameN.Spec
            ])
        }
        override func mo_model_reload() {
            iconN.image = UIImage(share_named: mo.model["icon",""])
            nameN.attributedText = mo.model["title",""].ui.font10.color(color: Setting.foregroundColor).astring
        }
    }
    
    let bridge = ASBridge()
    let content = Content()
    class Content:MoDisplayNode,ASCollectionDelegate,ASCollectionDataSource,JoTableCellDelegate{
        let canleBt = ASButtonNode()
        
        var confirmItem:(_:NSMutableDictionary)->Void = {_ in}
        
        func touch(cell: Any, actionID: String, model: NSMutableDictionary) {}
        var row1:NSMutableArray = Setting.shareItems.mutable_array{
            didSet{
                rowNode1.reloadData()
            }
        }
        
        var row2:NSMutableArray = Setting.actionItems.mutable_array{
            didSet{
                rowNode2.reloadData()
            }
        }
        
        lazy var rowNode1:ASCollectionNode = {
            let flow = UICollectionViewFlowLayout()
            flow.sectionInset = [0,Setting.padding.left]
            flow.minimumInteritemSpacing = Setting.iconSpace
            flow.minimumLineSpacing = Setting.iconSpace
            flow.scrollDirection = .horizontal
            
            flow.itemSize = Setting.iconSize
            let node = ASCollectionNode(collectionViewLayout: flow)
            node.view.showsHorizontalScrollIndicator = false
            node.view.backgroundColor = .clear
            node.delegate = self
            node.dataSource = self
            return node
        }()
        
        lazy var rowNode2:ASCollectionNode = {
            let flow = UICollectionViewFlowLayout()
            flow.sectionInset = [0,Setting.padding.left]
            flow.minimumInteritemSpacing = Setting.iconSpace
            flow.minimumLineSpacing = Setting.iconSpace

            flow.itemSize = Setting.iconSize
            let node = ASCollectionNode(collectionViewLayout: flow)
            node.view.backgroundColor = .clear
            node.delegate = self
            node.dataSource = self
            return node
        }()
        
        
        func confirm(item:NSMutableDictionary) {
            confirmItem(item)
            
        }
        override func addLayoutRules() {
            sperator.view.backgroundColor = ._separator
            rowNode1.reloadData()
            rowNode2.reloadData()
            titleL.attributedText = "分享到".loc.ui.font14.color(color: ._foreground).astring
        }
        
        func collectionNode(_ collectionNode: ASCollectionNode, didSelectItemAt indexPath: IndexPath) {
            if collectionNode === rowNode1{
                if let md = row1[indexPath.item] as? NSMutableDictionary{
                    confirm(item: md)
                }
                return
            }
            if let md = row2[indexPath.item] as? NSMutableDictionary{
                
                confirm(item: md)
            }
        }
        
        
        func collectionNode(_ collectionNode: ASCollectionNode, numberOfItemsInSection section: Int) -> Int {
            if collectionNode === rowNode1{
                return row1.count
            }
            return row2.count
        }
        
        func numberOfSections(in collectionNode: ASCollectionNode) -> Int {
            return 1
        }
        
        func collectionNode(_ collectionNode: ASCollectionNode, nodeForItemAt indexPath: IndexPath) -> ASCellNode {
            let cell = Kit()
            cell.delegate = self
            if collectionNode === rowNode1{
                if let md = row1[indexPath.item] as? NSMutableDictionary{
                    cell.mo.model = md
                }
            }else{
                if let md = row2[indexPath.item] as? NSMutableDictionary{
                    cell.mo.model = md
                }
            }
            return cell
        }
        
        let sperator = ASDisplayNode()
        let titleL = ASTextNode2()

        override func specGetter() -> _Spec {
            return .inset([],[16,0], child: .stack(["v|8",&-.stretch], childs: [
                titleL["20",[8,Setting.padding.left,8,Setting.padding.right]],
                rowNode1["\(Setting.iconSize.height + 1)"],
                .inset([], [10,Setting.padding.left], child: sperator["\(TP.separatorHeight)"]),
                rowNode2["\(Setting.iconSize.height + 1)"],
            ]))
        }
    }
    deinit {
    }
}

